package com.wl.jetpackdemo.banner

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.wl.jetpackdemo.base.BaseViewModel
import com.wl.jetpackdemo.base.db.DBManager
import com.wl.jetpackdemo.base.db.user.User
import com.wl.jetpackdemo.base.network.NetReqData
import com.wl.jetpackdemo.base.network.NetRequestManager
import com.wl.wllite.net.exception.ErrorStatus
import com.wl.wllite.net.exception.ExceptionHandle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * Created by wangliang on 2021/1/28.
 */
class BannerViewModel: BaseViewModel() {
    var pIndex = MutableLiveData<Int>() //列表分页当前索引值
    var netBannerListData = MutableLiveData<NetReqData<List<Banner>>>()


    fun setPageIndex(p: Int) {
        pIndex.value = p
    }

    fun getPageIndex() : Int{
        if(pIndex.value == null) {
            return 0
        } else {
            return pIndex.value!!
        }
    }


    fun saveAndQueryUser() {

        viewModelScope.launch {
            // 插入数据方法
//            withContext(Dispatchers.IO) {
//                DBManager.db().userDao().insert(User("test3", 3, "哈哈"))
//            }


            // 条件查询方法
//            var user = withContext(Dispatchers.IO) {
//                DBManager.db().userDao().getById(2)
//            }

            //删除数据 指定id即可删除对应数据
//            withContext(Dispatchers.IO) {
//                var user = User()
//                user.id = 2
//                DBManager.db().userDao().delete(user)
//            }

            // 查询所有数据方法
            var users = withContext(Dispatchers.IO) {
                DBManager.db().userDao().getAll()
            }


            for(user in users) {
                Log.d("WLTest", "user ${user.id
                }, name: ${user.name} : ${user.age}, desc: ${user.desc}")
            }
        }

    }



    fun getBanners(pageIndex: Int) {
        /* viewModelScope是一个绑定到当前viewModel的作用域  当ViewModel被清除时会自动取消该作用域，所以不用担心内存泄漏为问题*/
        viewModelScope.launch {
            try {
                val resp = withContext(Dispatchers.IO) {
                    NetRequestManager.apiService().getBanners()
                }
                if(resp.code == ErrorStatus.SUCCESS) {
                    netBannerListData.value = NetReqData(resp.code, resp.msg, resp.data)
                } else {
                    Log.e("WLTest", "请求失败 ${resp.msg}(${resp.code})")
                    netBannerListData.value = NetReqData(resp.code, resp.msg, resp.data)
                }
            } catch (t : Throwable) {
                ExceptionHandle.handleException(t)
                Log.i("WLTest", "请求失败 ${ExceptionHandle.errorMsg}(${ExceptionHandle.errorCode})")
                netBannerListData.value = NetReqData(ExceptionHandle.errorCode, ExceptionHandle.errorMsg, null)
            }
        }
    }
}